﻿
using visinia.SmartEngine.Providers;
using System;
using System.Collections.Generic;
using visinia.SmartEngine.Cache;
using System.Data;
namespace visinia.SmartEngine.Log
{
    public class LogController
    {
        public static void AddLog(string message)
        {
            string CurrentUser = System.Threading.Thread.CurrentPrincipal.Identity.Name;
            AddLog(CurrentUser, message);
            DataCache.DeleteCacheMultiple("log");           

        }

        private static void AddLog(string user, string message)
        {
            SmartEngineDataProvider.Provider.AddLog(user, DateTime.Now, message);
        }

        public static List<Activity> GetLog()
        {
            string key = "log";
            List<Activity> log = (List<Activity>)DataCache.GetCache(key);
            if (log == null)
            {
                log = FillLog(SmartEngineDataProvider.Provider.GetLog());
                DataCache.SetCache(key, log, new TimeSpan(0, 30, 0));
            }
            return log;
        }

        #region PRIVATE METHODS
        private static List<Activity> FillLog(IDataReader dr)
        {
            List<Activity> list = new List<Activity>();
            while (dr.Read())
            {
                list.Add(ActualRead(dr));
            }
            dr.Close();
            return list;
        }

        /// <summary>
        /// The actual read
        /// </summary>
        private static Activity ActualRead(IDataReader dr)
        {
            Activity activity = new Activity();
            if (dr["ActivityId"] != Convert.DBNull)
                activity.ActivityId = (int)dr["ActivityId"];
            if (dr["User"] != Convert.DBNull)
                activity.User = (string)dr["User"];
            if (dr["Date"] != Convert.DBNull)
                activity.Date = (DateTime)dr["Date"];
             if (dr["Message"] != Convert.DBNull)
                activity.Message = (string)dr["Message"];
            return activity;
        }
        #endregion
    }
}
